<template>
  <view>
    <view class="search_row">
      <input :value="inpValue" placeholder="请输入您要搜索的商品" @input="handleInput" />
      <button @click="handleCancel" :hidden="!isFocus">取消</button>
    </view>
    <view class="search_content">
      <navigator :url="`/pages/goods_detail/goods_detail?goods_id=${item.goods_id}`" class="search_item"
        v-for="item in goods" :key="item.goods_id">
        {{item.goods_name}}
      </navigator>
    </view>
  </view>
</template>

<script>
import request from "../../utils/request";
export default {
  data() {
    return {
      goods: [],
      // 取消 按钮 是否显示
      isFocus: false,
      // 输入框的值
      inpValue: "",
      TimeId: -1,
    };
  },
  methods: {
    // 输入框的值改变 就会触发的事件
    handleInput(e) {
      // 1 获取输入框的值
      const { value } = e.detail;
      console.log(value, "value");
      // 2 检测合法性
      if (!value.trim()) {
        this.goods = [];
        this.isFocus = false;
        // 值不合法
        return;
      }
      // 3 准备发送请求获取数据

      this.isFocus = true;

      clearTimeout(this.TimeId);
      this.TimeId = setTimeout(() => {
        this.qsearch(value);
      }, 1000);
    },
    // 发送请求获取搜索建议 数据
    async qsearch(query) {
      const res = await request("/goods/qsearch", { query });
      console.log(res);
      this.goods = res.message;
    },
    // 点击 取消按钮
    handleCancel() {
      this.inpValue = "";
      this.isFocus = false;
      this.goods = [];
    },
  },
};
</script>

<style lang="less">
.search_row {
  height: 60rpx;
  display: flex;
  input {
    background-color: #fff;
    flex: 1;
    height: 100%;
    padding-left: 30rpx;
    border: 1px solid black;
  }
  button {
    width: 110rpx;
    height: 100%;
    padding: 0;
    margin: 5rpx 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 26rpx;
    background-color: #ccc;
  }
}

.search_content {
  margin-top: 30rpx;
  .search_item {
    background-color: #fff;
    font-size: 26rpx;
    padding: 15rpx 10rpx;
    border-bottom: 1rpx solid #ccc;

    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
